package com.orangecy.common.util;

import com.orangecy.common.anno.LbFieldDiff;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @Author : orangeCy.奕
 * @Time : 2021/9/30
 * @desc : 猎豹养成产品源码
 */
public class LbFieldDiffUtils {

    private LbFieldDiffUtils(){}

    public static <T> boolean isChanged(T source, T target) {
        if (source == null || target == null) {
            return false;
        }
        Field[] sourceFields = source.getClass().getDeclaredFields();
        if (null == sourceFields || sourceFields.length == 0) {
            return false;
        }
        boolean isChanged;
        for (Field sf : sourceFields) {
            if (sf.isAnnotationPresent(LbFieldDiff.class)) {
                sf.setAccessible(true);
                Object sourceFieldVal = getFieldValueByFieldName(sf.getName(), source);
                Object targetFieldVal = getFieldValueByFieldName(sf.getName(), target);
                if (null == sourceFieldVal) {
                    isChanged = (targetFieldVal != null);
                } else {
                    isChanged = !sourceFieldVal.equals(targetFieldVal);
                }
                if(isChanged){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 为了测试ReflectionUtils需要Spring环境
     *
     * @param fieldName
     * @param object
     * @return
     */
    private static String getFieldValueByFieldName(String fieldName, Object object) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = object.getClass().getMethod(getter, new Class[]{});
            Object value = method.invoke(object, new Object[]{});
            return value.toString();
        } catch (Exception e) {
            return "exception";
        }
    }
}